package com.hugh.blog_cache.controller;

import com.hugh.blog_cache.entity.RequestEntity;
import com.hugh.blog_cache.entity.ResponseEntity;
import com.hugh.blog_cache.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Objects;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

/**
 * @Author: Hugh
 * @Date: 2020/5/25
 */
@Controller
@Slf4j
public class BlogController {

    @Autowired
    private ArticleService articleService;

    @RequestMapping("/index")
    public String blogIndexView(RequestEntity requestEntity, Model model){
        if(Objects.isNull(requestEntity)){
            requestEntity = RequestEntity.builder().pageSize(10).pageNum(1).build();
        }
        ResponseEntity responseEntity = articleService.queryAllArticlesByCondition(requestEntity);
        model.addAttribute("totalCount", responseEntity.getCount());
        Integer pageCount = responseEntity.getCount() / requestEntity.getPageSize();
        if(responseEntity.getCount() % requestEntity.getPageSize() != 0){
            pageCount++;
        }
        model.addAttribute("pageCount", pageCount);
        model.addAttribute("currentPage", requestEntity.getPageNum());
        model.addAttribute("articles", responseEntity.getArticles());
        log.info("requestEntity:{}, responseEntity{}", requestEntity.toString(), responseEntity.toString());
        return "index";
    }
}
